const computedBehavior = require('miniprogram-computed')
//获取应用实例
const app = getApp()
//每次缩小或者放大的系数
let zoomSpeed = 0.01;
//promise化
let wxp = {
    getImageInfo: app.promisify(wx.getImageInfo)
}

Page({
    behaviors: [computedBehavior],
    data: {
        userInfo: {},
        hasUserInfo: false,
        canIUse: wx.canIUse('button.open-type.getUserInfo'),
        width: 250, //宽度
        height: 250, //高度
        isCuting: false,
        cutImgSrc: 'https://www.youyi.asia/assets/img/wxminiAvatarFrame/1.png',
        scale: 1,
        imgUrl: '',
        coverImgUrl: ''
    },
    computed: {
        isShowZoom(data) {
            // 注意： computed 函数中不能访问 this ，只有 data 对象可供访问
            // 这个函数的返回值会被设置到 this.data.sum 字段中
            return !!data.imgUrl
        },
        isShowDownload(data) {
            return !!(data.imgUrl && data.coverImgUrl)
        },
    },
    onLoad: function () {
        this.queryCovers()
        this.setUserInfo();

    },

    //滑动缩放
    sliderchange(e) {
        let v = e.detail.value;
        let scale = v / 100;
        this.setData({
            scale
        })
    },

    //下载
    saveToPhone() {
        if (!this.data.imgUrl || !this.data.coverImgUrl) {
            wx.showToast({
                title: '请选择照片和封面',
                icon: 'none'
            })
            return;
        }
        wx.showLoading({
            title: '正在保存...',
        })
        const ctx = wx.createCanvasContext('my-canvas')
        //画网络图片
        let p1 = wxp.getImageInfo({
            src: this.data.coverImgUrl
        });
        let p2 = wxp.getImageInfo({
            src: this.data.imgUrl
        })
        Promise.all([p1, p2]).then(([coverRes, imgRes]) => {
            //画底图的时候需要考虑缩放，需要计算x y width height
            let dx, dy, dWidth, dHeight;
            let scale = this.data.scale;
            dWidth = dHeight = 300 * scale;
            dx = dy = (300 - dWidth) / 2;
            ctx.drawImage(imgRes.path, dx, dy, dWidth, dHeight)
            ctx.drawImage(coverRes.path, 0, 0, 300, 300)
            ctx.draw(false, () => {
                wx.canvasToTempFilePath({
                    x: 0,
                    y: 0,
                    width: 300,
                    height: 300,
                    canvasId: 'my-canvas',
                    success: function (res) {
                        wx.saveImageToPhotosAlbum({
                            filePath: res.tempFilePath, //canvasToTempFilePath返回的tempFilePath
                            success: (res) => {
                                wx.hideLoading();
                            },
                            fail(err) {
                                console.error(err)
                                wx.hideLoading()
                            }
                        })
                    },
                    fail(err) {
                        console.error(err)
                        wx.hideLoading()
                    }
                })
            });
        }).catch(err => {
            console.error(err)
            wx.hideLoading()
        })
    },

    //选择图片开始上传
    chooseImg() {
        let self = this;
        wx.chooseImage({
            sizeType: ['original', 'compressed'],
            sourceType: ['album'],
            success(res) {
                let url = res.tempFilePaths[0]
                self.setData({
                    cutImgSrc: url, //前端显示图片
                    isCuting: true
                })
            }
        })
    },

    loadimage(e) {
        //重置图片角度、缩放、位置
        this.selectComponent("#image-cropper").imgReset();
    },

    //裁剪确定
    onCutFinish() {
        this.selectComponent("#image-cropper").getImg((obj) => {
            let url = obj.url;
            this.setData({
                imgUrl: url,
                isCuting: false
            })
        });
    },
    //授权按钮的回调
    getUserInfo: function (e) {
        //把头像变成高清头像
        e.detail.userInfo.avatarUrl = this.convert2HD(e.detail.userInfo.avatarUrl)
        app.globalData.userInfo = e.detail.userInfo
        this.setData({
            userInfo: e.detail.userInfo,
            hasUserInfo: true,
            imgUrl: e.detail.userInfo.avatarUrl
        })
    },
    //使用微信头像
    useWxAvatar() {
        this.setData({
            imgUrl: this.convert2HD(this.data.userInfo.avatarUrl)
        })
    },
    //将用户信息setdata中
    setUserInfo() {
        if (app.globalData.userInfo) {
            this.setData({
                userInfo: app.globalData.userInfo,
                hasUserInfo: true
            })
        } else if (this.data.canIUse) {
            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
            // 所以此处加入 callback 以防止这种情况
            app.userInfoReadyCallback = res => {
                this.setData({
                    userInfo: res.userInfo,
                    hasUserInfo: true
                })
            }
        } else {
            // 在没有 open-type=getUserInfo 版本的兼容处理
            wx.getUserInfo({
                success: res => {
                    app.globalData.userInfo = res.userInfo
                    this.setData({
                        userInfo: res.userInfo,
                        hasUserInfo: true
                    })
                }
            })
        }
    },

    /**
     * 把普通大小的头像转换为HD头像
     */
    convert2HD(imageUrl) {
        imageUrl = imageUrl.split('/'); //把头像的路径切成数组
        //把大小数值为 46 || 64 || 96 || 132 的转换为0
        if (imageUrl[imageUrl.length - 1] && (imageUrl[imageUrl.length - 1] == 46 || imageUrl[imageUrl.length - 1] == 64 || imageUrl[imageUrl.length - 1] == 96 || imageUrl[imageUrl.length - 1] == 132)) {
            imageUrl[imageUrl.length - 1] = 0;
        }
        imageUrl = imageUrl.join('/'); //重新拼接为字符串
        return imageUrl;
    },
    //查询照片封面
    queryCovers() {
        let self = this;
        wx.request({
            url: 'https://www.youyi.asia/assets/img/wxminiAvatarFrame/data.json',
            success({
                data: covers
            }) {
                self.setData({
                    covers,
                    coverImgUrl: covers[0].url
                })
            }
        })
    },
    //改变封面
    changePhoto(e) {
        let coverImgUrl = e.target.dataset.url;
        this.setData({
            coverImgUrl
        })
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})